package com.develop.skwen.ourrules.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.develop.skwen.ourrules.basic.Presenter;
import com.develop.skwen.ourrules.basic.Vu;

/**
 * Created by skwen
 * on 18-4-24
 */

public abstract class BaseFragment<P extends Presenter,V extends Vu> extends Fragment {

    private boolean mIsVisibleToUser,mIsViewCreated;
    private V mV;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.mIsVisibleToUser = isVisibleToUser;
        if (isVisibleToUser){
            showViewFragment();
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mIsViewCreated = true;
        showViewFragment();
    }

    private void showViewFragment() {
        if (mIsVisibleToUser && mIsViewCreated){
            onBind();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        try {
            mV = getVuClass().newInstance();
            mV.setActivity(getActivity());
            mV.setPresenter(getPresenter());
            mV.init();
            return mV.getView();
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


        return super.onCreateView(inflater, container, savedInstanceState);
    }

    public V getVu() {
        return mV;
    }

    /**
     * 布局view类
     * @return
     */
    protected abstract Class<? extends V> getVuClass();

    /**
     * 业务操作类
     * @return
     */
    protected abstract P getPresenter();

    /**
     * view初始化完成后可用此方法获取数据
     */
    protected abstract void onBind();

}
